import { fetchMenuList } from '@/api/user'
import { defineStore } from 'pinia'
import { RouteRecordRaw } from 'vue-router'
import router, { routes as constantRoutes } from '@/router'
import type { PermissionStore } from './types'
import { useUserInfo } from '@/hooks/core/useUserInfo'
import { handleTree } from '@/utils'
import { ToBool } from '@/config/constants'
import ParentView from '@/components/ParentView/index.vue'

const modules = import.meta.glob('../../../views/**/**.vue', { eager: true, import: 'default' })
export const Layout = () => import('@/layouts/index.vue')

export const filterAsyncRoutes = (routes: RouteRecordRaw[]) => {
  const res: RouteRecordRaw[] = []

  Array.isArray(routes) &&
    routes.forEach((route) => {
      const tmp = { ...route } as any
      if (tmp.component === 'Layout') {
        tmp.component = Layout
      } else if (tmp.component === 'ParentView') {
        tmp.component = ParentView
        // console.log('tmp.href', tmp.href)
        tmp.children = [{ component: tmp.href }]
      } else {
        const component = modules[`../../../views${tmp.component}/index.vue`] as any

        if (component) {
          tmp.component = modules[`../../../views${tmp.component}/index.vue`]
        } else {
          tmp.component = modules[`@/views/error/404/index.vue`]
        }
      }

      if (!tmp.meta) {
        tmp.meta = {}
      }

      tmp.name = tmp.href?.slice(1).replace(/\//g, '-')
      tmp.label = tmp?.title || ''
      tmp.path = tmp?.href || ''
      tmp.meta.title = tmp?.title || tmp.label || ''
      tmp.meta.icon = tmp?.iconName || ''
      tmp.meta.hidden = ToBool[tmp?.hidden] || false

      tmp.component && res.push(tmp)

      if (tmp.children && tmp.component !== 'ParentView') {
        tmp.children = filterAsyncRoutes(tmp.children)
      }
    })

  return res
}

const usePermissionStore = defineStore('permission', {
  state: (): PermissionStore => ({
    registerRouteFresh: true,
    routes: [],
    addRoutes: [],
  }),

  actions: {
    async reset() {
      this.$reset()
    },
    setRoutes(routes: RouteRecordRaw[]) {
      this.addRoutes = routes
      this.routes = constantRoutes.concat(routes)
    },
    generateRoutes() {
      const userInfo = useUserInfo()
      if (!userInfo) {
        router.push('/login')
        return
      }

      return new Promise((resolve, reject) => {
        fetchMenuList(userInfo.id)
          .then((res: any) => {
            const accessedRoutes = filterAsyncRoutes(handleTree(res?.menus))
            this.setRoutes(accessedRoutes)
            resolve(accessedRoutes)
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
  },
})

export default usePermissionStore
